package com.intpro.demo.Controller;

import java.io.File;
import java.io.IOException;

import java.util.UUID;
import org.springframework.web.multipart.MultipartFile;

public class FileUploadController
{

	/**
	 * 返回唯一标识符
	 *
	 * @return String
	 **/
	public static String getUUID()
	{
		return UUID.randomUUID().toString().replace("-", "");
	}

	public static String getSuffix(String fileName)
	{
		return fileName.substring(fileName.lastIndexOf('.'));
	}

	public static String getFileName(String fileOriginName)
	{
		return getUUID() + getSuffix(fileOriginName);
	}

	/**
	 * 将文件保存到/resources/public/photos/下面，以便静态访问
	 *
	 * @param file 需要保存的文件
	 * @return String 静态文件访问的url
	 **/
	public static String saveFile(MultipartFile file, String uploadPath, String xdp)
			throws IOException
	{
		String nname = getFileName(file.getOriginalFilename());
		uploadPath += xdp;
		File path = new File(uploadPath);
		if (!path.exists())
		{
			path.mkdir();
			//path = new File("");
		}
		File dest = new File(path.getAbsolutePath() + "/" + nname);
		if (!dest.getParentFile().exists())
		{

			dest.getParentFile().mkdirs();
		}
		file.transferTo(dest);
		return "api/files/" + xdp + nname;
	}
}
